#coding=utf-8
import imghdr
import types
import uuid
from io import BytesIO

import requests
# py http 工具类 包括客户端异常处理，断线重连，事务回滚回调函数等
from PIL import Image

class HttpUtil:

    # post url + json
    def post(self, url, json, fun):
        try:
            headers = {'Content-Type': 'application/json; charset=utf-8'}
            res = requests.post(url, json=json, headers=headers)
            return res.json()
        except BaseException as e:
            print(e)
            # 回调函数 回滚用
            if isinstance(fun, types.FunctionType):
                fun()
            # 如果发生http 异常或者 json转换异常，则返回字符串响应内容
            return res.text

    # POST一个多部分编码(Multipart-Encoded)的文件
    # data : json参数，以表单方式提交
    # files : 文件参数，以流表单的方式提交
    def post_file(self, url, data, files):
        try:
            r = requests.post(url,data = data,files = files)
            return r.json()
        except BaseException as e:
            print(e)
            return r.text

    # 提交表单数据 - post方式
    def post_form_data(self, url, data):
        try:
            r = requests.post(url, data = data)
            return r.json()
        except BaseException as e:
            print(e)
            return r.text

    # 提交表单数据 - get方式
    def get(self, url, param, fun):
        try:
            res = requests.get(url, params = param)
            return res.json()
        except BaseException as e:
            print(e)
            # 回调函数 回滚用
            if isinstance(fun, types.FunctionType):
                fun()
            # 如果发生http 异常或者 json转换异常，则返回字符串响应内容
            return res.text

    # 暂存图片于本地
    def get_pic_content(self, img_src):
        try:
            local_path = "E:/lgy/net_resource/spider_pic/"
            response = requests.get(img_src)
            # 识别图片后缀
            pic_suffix = imghdr.what(None, response.content)
            image = Image.open(BytesIO(response.content))
            file_uuid = uuid.uuid4()
            file_path = local_path + str(file_uuid) + "." + pic_suffix
            image.save(file_path)
            res_dict = {"file_path" : file_path ,"pic_suffix": pic_suffix}
            return res_dict
        except BaseException as e:
            print(e)
            return
# 模块单例
http_util = HttpUtil()

